package org.sdnstproject.interlayer.OF10Protocal;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Random;

import org.projectfloodlight.openflow.types.U16;
import org.projectfloodlight.openflow.types.U32;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

public class FuEchoReplyV10 {
	private static final Logger log = LoggerFactory.getLogger(FuEchoReplyV10.class);
    public byte version = (byte)1;
    public byte type = (byte)3;
    public short length = (short)8;//MINIMUM_LENGTH = 8;
    public long xid = 0x0L;
	public byte[] data = new byte[] {};//Usually 0
	
	public FuEchoReplyV10() {
		
	}
	    	
	public FuEchoReplyV10 setXid(long xid) {
		this.xid = xid;
		return this;
	}
	
    public FuEchoReplyV10 setField(String field, String value) {
		switch (field) {
		case "version":
			this.version = Byte.parseByte(value);
			break;
		case "type":
			this.type = Byte.parseByte(value);
			break;
		case "length":
			this.length = Short.parseShort(value);
			break;
		case "xid":
			this.xid = Long.parseLong(value);
			break;
		case "data":
			this.data = new byte[new Random().nextInt(3)];
			new Random().nextBytes(data);
			break;
		}
		return this;
	}
    
    
	public ByteBuf writeTo() {
		ByteBuf bb = Unpooled.directBuffer();
        int startIndex = bb.writerIndex();
        // fixed value property version = 1
        bb.writeByte(version);
        // fixed value property type = 3
        bb.writeByte(type);
        // length is length of variable message, will be updated at the end
        int lengthIndex = bb.writerIndex();
        bb.writeShort(U16.t(0));

        bb.writeInt(U32.t(xid));
        bb.writeBytes(data);

        // update length field
        length = (short)(bb.writerIndex() - startIndex);
        bb.setShort(lengthIndex, length);
        return bb;
    }
	@Override
    public String toString() {
        StringBuilder b = new StringBuilder("OFEchoReplyVer10(");
        b.append("version=").append(version);
        b.append(", ");
        b.append("type=").append(type);
        b.append(", ");
        b.append("length=").append(length);
        b.append(", ");
        b.append("xid=").append(xid);
        b.append(", ");
        b.append("data=").append(Arrays.toString(data));
        b.append(")");
        return b.toString();
    }
}
